<?php


namespace App\Customer\Controller;

use App\Customer\Model\CaseModel;
use App\Service\ExternalAPI\EhireApi;
use EchoPHP\Facades\Db;
use EchoPHP\Http\Request;
use App\Web\Model\EhireUser as UserModel;
use App\Customer\Model\ResumeRecommend as RecommendModel;

class User extends Controller {

    /**获取用户信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserInfo(Request $request) {
        $ehireApi = new EhireApi();
        $accessKey = $this->getEhireAccessKey();
        $myhruid = $this->getEhireHruid();                   //操作人的hruid
        $userModel = new UserModel();
        $oprRole = $userModel->getEhireRole($myhruid);
        $hruid = $request->getParam('hruid', 0); //被获取的hruid

        if (!in_array($oprRole, [1, 2]) && $hruid != $myhruid) {
            $resultBody = [
                'code' => 99999,
                'msg' => '无权限进行操作',
                'data' => []
            ];
            return $this->json($resultBody);
        }

        $resultBody = $ehireApi->getUserInfo($accessKey, $hruid);

        return $this->json(
            $resultBody
        );
    }

    /**
     * 重新发送邮件
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function resendNewUserVerifyEmail(Request $request) {
        $ehireApi = new EhireApi();
        $myhruid = $this->getEhireHruid();
        $accessKey = $this->getEhireAccessKey();
        $hrUid = $request->getPost('hruid', 0);
        $userModel = new UserModel();
        $oprRole = $userModel->getEhireRole($myhruid);
        if (!in_array($oprRole, [1, 2])) {
            $resultBody = [
                'code' => 99999,
                'msg' => '无权限进行操作',
                'data' => []
            ];
            return $this->json($resultBody);
        }
        $resultBody = $ehireApi->resendNewUserVerifyEmail($accessKey, $hrUid);

        return $this->json(
            $resultBody
        );
    }

    /**验证key是否有效
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function checkAccessKey(Request $request) {
        $ehireApi = new EhireApi();
        $accessKey = $this->getEhireAccessKey();

        $resultBody = $ehireApi->checkAccessKey($accessKey);

        return $this->json(
            $resultBody
        );
    }

    /**
     * 新增用户
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addUser(Request $request) {
        $accessKey = $this->getEhireAccessKey();
        $userName = $request->getPost('username', '');
        $name = $request->getPost('name', '');
        $email = $request->getPost('email', '');
        $role = $request->getPost('role', 9);

        $myhruid = $this->getEhireHruid();
        $myCtmId = $this->getEhireCtmid();

        $userModel = new UserModel();
        $resultBody = $userModel->addUser($accessKey, $role, $userName, $name, $email, $myhruid, $myCtmId);

        return $this->json($resultBody);
    }

    /**
     * 添加已有用户
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addExistUser(Request $request) {
        $accessKey = $this->getEhireAccessKey();
        $hrUid = $request->getPost('hruid', 0);
        $role = $request->getPost('role', 9);
        $myhruid = $this->getEhireHruid();
        $myCtmId = $this->getEhireCtmid();

        $userModel = new UserModel();
        $resultBody = $userModel->addExistUser($accessKey, $hrUid, $role, $myhruid, $myCtmId);

        return $this->json($resultBody);
    }

    /**
     * 修改用户信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateUserInfo(Request $request) {
        $accessKey = $this->getEhireAccessKey();
        $myhruid = $this->getEhireHruid();
        $email = $request->getPost('email', '');
        $hrUid = $request->getPost('hruid', 0);
        $userName = $request->getPost('username', '');
        $name = $request->getPost('name', '');
        $role = $request->getPost('role');

        $userModel = new UserModel();
        $myCtmId = $this->getEhireCtmid();
        $resultBody = $userModel->updateUserInfo($accessKey, $role, $hrUid, $email, $userName, $name, $myhruid, $myCtmId);

        return $this->json($resultBody);
    }

    /**
     * 删除用户
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function deleteUsers(Request $request) {
        $accessKey = $this->getEhireAccessKey();
        $myHrUid = $this->getEhireHruid();
        $hruids = $this->request->getParam('hruids', '');

        $userModel = new UserModel();
        $resultBody = $userModel->deleteUsers($accessKey, $hruids, $myHrUid);

        return $this->json(
            $resultBody
        );
    }

    /**
     * 获取用户列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserList(Request $request) {
        $accessKey = $this->getEhireAccessKey();
        $myHrUid = $this->getEhireHruid();
        $ctmId = $this->getEhireCtmid();
        $pageIndex = $request->getPost('pagenum');
        $pageSize = $request->getPost('pagelimit');
        $sort = $request->getPost('sort','createtime|1');
        $where = [
            'username' => $request->getPost('username'),
            'email' => $request->getPost('email'),
            'name' => $request->getPost('mobile'),
            'hruids' => $request->getPost('hruids'),
            'activestatus' => $request->getPost('activestatus')
        ];

        $whereString = '';
        foreach ($where as $key => $item) {
            if ($item != null) {
                $whereString .= $key . '|' . urlencode($item) . '&';
            }
        }
        $whereString = trim($whereString, '&');
        $userModel = new UserModel();
        $resultBody = $userModel->getUserList($accessKey, $pageIndex, $pageSize, $sort, $whereString, $myHrUid,$ctmId);

        return $this->json(
            $resultBody
        );
    }

    /**
     * 获取用户推荐列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getRecommendList(Request $request) {
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pagelimit/d', 10);
        $subId = $request->getParam('subid/d', 0);

        $caseModel = new CaseModel();
        $hrUid = $this->getEhireHruid();
        $subIds = $this->getSubIds();
        //判断用户是否和subid有关联
        if (empty($subId) || !$caseModel->checkSubIdByHrUid($subIds, $subId)) {
            return $this->json([
                'status' => false,
                'message' => '参数出錯！'
            ]);
        }



        $search = [];
        $search['subId'] = $subId;
        $search['createdatebegin'] = $request->getParam('createdatebegin');
        $search['createdateend'] = $request->getParam('createdateend');
        $hruId = $this->getEhireHruid();
        $recommendModel = new RecommendModel();
        $count = $recommendModel->getToMyRecommendCount($hruId, $search);
        $resultBody = [];
        $resultBody['totalCount'] = intval($count);
        $resultBody['pagenum'] = $pageNum;
        $resultBody['status'] = true;
        $resultBody['message'] = '获取成功';

        list($pageNum, $rowFrom, $rowTo) = $recommendModel->paginationParameters($pageNum, $pageLimit);

        $resultList = $recommendModel->getToMyRecommend($hruId, '', $search, $rowFrom, $rowTo);

        if (!empty($resultList)) {
            $subIds = array_column($resultList, 'subid');
            $inFlag = substr(str_repeat('? ,', (count($subIds))), 0, -1);
            $sql = 'select subid,subname from CustomerSub where subid in (' . $inFlag . ')';
            $var = $subIds;
            $subList = Db::select($sql, $var);
            $subList = array_column($subList, null, 'subid');

            foreach ($resultList as $key => &$item) {
                $item['subname'] = $subList[$item['subid']]['subname'] ?? '';
                if ($item['firstopentime'] == "0000-00-00 00:00:00") {
                    $item['firstopentime'] = '';
                }else {
                    $item['firstopentime'] = !empty($item['firstopentime']) ? date("Y-m-d H:i", strtotime($item['firstopentime'])) : '';
                }
                if ($item['updatedate'] == "0000-00-00 00:00:00" || $item['updatedate'] == $item['createdate']) {
                    $item['updatedate'] = '';
                }else {
                    $item['updatedate'] = !empty($item['updatedate']) ? date("Y-m-d H:i", strtotime($item['updatedate'])) : '';
                }
                $item['createdate'] = !empty($item['createdate']) ? date("Y-m-d H:i", strtotime($item['createdate'])) : '';

                $duetime = strtotime(date("Y-m-d", time())) + 86400;
                $item['url'] = $recommendModel->creatRecommendToken($item['subid'], $item['id'], $duetime);
            }
        }

        $resultBody['resultList'] = $resultList;

        return $this->json($resultBody);
    }

    /**
     * 账号管理URL
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function ehireManageUrl(Request $request) {
        $accessKey = $this->getEhireAccessKey();
        $ehireApi = new EhireApi();
        $resultBody = $ehireApi->ehireManageUrl($accessKey);
        return $this->json(
            $resultBody
        );
    }

    /**
     * 退出登录
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function logout(Request $request) {

        $accessKey = $this->getEhireAccessKey();
        $ehireApi = new EhireApi();
        $resultBody = $ehireApi->logout($accessKey);

        //清除redis信息
        $hrUid = $this->getEhireHruid();
        $subIds = $this->getSubIds();
        $caseModel = new CaseModel();
        $caseModel->removeSubCase($hrUid, $subIds);
        return $this->json(
            $resultBody
        );
    }

    /**
     * 锁定或解锁用户
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function LookUnLookUser(Request $request) {
        $myhruid = $this->getEhireHruid();
        $myCtmid = $this->getEhireCtmid();
        $type = $request->getPost('type', 0);
        $role = $request->getPost('role');
        $hrUid = $request->getPost('hruid', 0);
        $ctmid= $request->getPost('ctmid', 0);
        // 1.锁定 2.解锁
        if(!in_array($type, array(1,2)) || empty($role) || empty($hrUid)){
            return $this->json(array(
                'code' => 99999,
                'message' => "传递的值出错！"
            ));
        }

        $userModel = new UserModel();
        $resultBody = $userModel->managerUser($role, $hrUid, $myhruid,$myCtmid,$ctmid, $type);

        return $this->json($resultBody);
    }
}